package com.youngcms.freemarker;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.youngcms.bean.Channel;
import com.youngcms.bean.Content;
import com.youngcms.freemarker.utils.Freemarker;
import com.youngcms.service.ChannelService;
import com.youngcms.service.ContentService;
import com.youngcms.vo.QueryResult;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.WrappingTemplateModel;
/**
 * 栏目列表
 * @author fumiao-pc
 *
 */
@Repository
public class ContentList implements TemplateDirectiveModel {
	
	@Autowired
	private ChannelService channelService;
	@Autowired
	private ContentService contentService;

	@Override
	public void execute(Environment env, Map map, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Integer model=Freemarker.getInteger(map, "model");
		String channelCode=Freemarker.getString(map, "channelCode");
		String fields=Freemarker.getString(map, "fields");
		String sort=Freemarker.getString(map, "sort");
		Integer size=Freemarker.getInteger(map, "size");
		Channel channel=channelService.selectByCode(channelCode);
		if(channel==null){
			channel=new Channel();
		}
		Content content=new Content();
		content.setChannelId(channel.getId());
		content.setModelId(model);
		if(size!=null){
			content.setPageRow(size);
		}
		if(StringUtils.isNotBlank(fields)){
			String orderBy="";
			String[] f=StringUtils.split(fields,",");
			String[] s=StringUtils.split(sort,",");
			for(int i=0;i<f.length;i++){
				orderBy=f[i]+" "+s[i];
			}
			content.setOrderBy("order by "+orderBy);
		}
		QueryResult<Content> queryResult=contentService.list(content);
		loopVars[0]= WrappingTemplateModel.getDefaultObjectWrapper().wrap(queryResult.getQueryResult());
		loopVars[1]= WrappingTemplateModel.getDefaultObjectWrapper().wrap(channel);
		body.render(env.getOut());
	}

}
